// 导入音频文件
import correctSound from '../assets/audio/t.mp3';
import wrongSound from '../assets/audio/a.mp3';
import successSound from '../assets/audio/s.mp3';
import failureSound from '../assets/audio/f.mp3';

class AudioPlayer {
  constructor() {
    this.audioContext = null;
    this.isAudioContextInitialized = false;
    this.audioBuffers = new Map();
    this.isPlaying = false;
    this.lastPlayTime = 0;
    this.debounceTime = 300; // 重新启用防抖，避免快速重复点击
    
    // 创建传统Audio对象作为fallback
    this.correctAudio = new Audio(correctSound);
    this.wrongAudio = new Audio(wrongSound);
    this.successAudio = new Audio(successSound);
    this.failureAudio = new Audio(failureSound);
    
    // 设置Audio对象属性
    this.setupAudioElements();
    
    // 预加载
    this.preload();
    
    // 绑定用户交互事件
    this.bindUserInteraction();
  }

  // 设置音频元素属性
  setupAudioElements() {
    const audioElements = [
      this.correctAudio,
      this.wrongAudio,
      this.successAudio,
      this.failureAudio
    ];
    
    audioElements.forEach(audio => {
      audio.preload = 'auto';
      audio.volume = 0.7; // 适当音量避免突然大声
    });
  }

  // 绑定用户交互事件以解锁音频
  bindUserInteraction() {
    const unlockAudio = () => {
      if (!this.isAudioContextInitialized) {
        this.initAudioContext().catch(console.error);
      }
      
      // 尝试播放静音音频来解锁传统Audio
      this.tryUnlockTraditionalAudio();
    };

    // 多种用户交互事件
    const events = ['click', 'touchstart', 'keydown', 'mousedown'];
    events.forEach(event => {
      document.addEventListener(event, unlockAudio, { once: true, passive: true });
    });
  }

  // 初始化AudioContext（更现代的音频API）
  async initAudioContext() {
    if (this.audioContext || !window.AudioContext) return;

    try {
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
      
      // 预加载所有音频为Buffer
      await this.preloadAudioBuffers();
      this.isAudioContextInitialized = true;
      
      console.log('AudioContext initialized successfully');
    } catch (error) {
      console.warn('AudioContext initialization failed, using traditional Audio:', error);
    }
  }

  // 预加载音频为Buffer
  async preloadAudioBuffers() {
    if (!this.audioContext) return;

    const audioFiles = [
      { key: 'correct', url: correctSound },
      { key: 'wrong', url: wrongSound },
      { key: 'success', url: successSound },
      { key: 'failure', url: failureSound }
    ];

    try {
      for (const file of audioFiles) {
        const response = await fetch(file.url);
        const arrayBuffer = await response.arrayBuffer();
        const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
        this.audioBuffers.set(file.key, audioBuffer);
      }
      console.log('All audio buffers preloaded');
    } catch (error) {
      console.warn('Audio buffer preloading failed:', error);
    }
  }

  // 尝试解锁传统Audio播放
  async tryUnlockTraditionalAudio() {
    const testAudio = new Audio();
    testAudio.volume = 0.001; // 几乎静音
    testAudio.preload = 'auto';
    
    try {
      await testAudio.play();
      // 立即暂停
      testAudio.pause();
    } catch (error) {
      console.warn('Traditional audio unlock failed:', error);
    }
  }

  // 播放音频（优先使用AudioContext，降级到传统Audio）
  async playAudio(audioElement, bufferKey) {
    const now = Date.now();
    
    // 防抖处理
    if (now - this.lastPlayTime < this.debounceTime) {
      return;
    }
    
    this.lastPlayTime = now;

    try {
      // 优先使用AudioContext
      if (this.isAudioContextInitialized && this.audioBuffers.has(bufferKey)) {
        await this.playWithAudioContext(bufferKey);
      } else {
        // 降级到传统Audio
        await this.playWithTraditionalAudio(audioElement);
      }
    } catch (error) {
      console.warn(`Audio play failed for ${bufferKey}, trying fallback:`, error);
      
      // 最终fallback
      try {
        await this.playWithTraditionalAudio(audioElement);
      } catch (finalError) {
        console.error('All audio playback methods failed:', finalError);
      }
    }
  }

  // 使用AudioContext播放
  async playWithAudioContext(bufferKey) {
    if (!this.audioContext || !this.audioBuffers.has(bufferKey)) {
      throw new Error('AudioContext not ready');
    }

    const source = this.audioContext.createBufferSource();
    source.buffer = this.audioBuffers.get(bufferKey);
    source.connect(this.audioContext.destination);
    source.start(0);
    
    // 清理资源
    source.onended = () => {
      source.disconnect();
    };
  }

  // 使用传统Audio元素播放
  async playWithTraditionalAudio(audioElement) {
    if (!audioElement) {
      throw new Error('Audio element not available');
    }

    // 克隆音频元素避免冲突
    const audioClone = audioElement.cloneNode();
    audioClone.volume = audioElement.volume;
    
    // 重置播放位置
    audioClone.currentTime = 0;
    
    await audioClone.play();
    
    // 播放结束后清理
    audioClone.onended = () => {
      audioClone.remove();
    };
  }

  // 播放正确音效
  playCorrect = () => {
    this.playAudio(this.correctAudio, 'correct');
  }

  // 播放错误音效
  playWrong = () => {
    this.playAudio(this.wrongAudio, 'wrong');
  }

  // 播放成功音效
  playSuccess = () => {
    this.playAudio(this.successAudio, 'success');
  }

  // 播放失败音效
  playFailure = () => {
    this.playAudio(this.failureAudio, 'failure');
  }

  // 预加载音频
  preload() {
    const audioElements = [
      this.correctAudio,
      this.wrongAudio,
      this.successAudio,
      this.failureAudio
    ];
    
    audioElements.forEach(audio => {
      audio.load();
    });
  }

  // 恢复音频上下文（用于处理页面隐藏后的恢复）
  resumeAudioContext() {
    if (this.audioContext && this.audioContext.state === 'suspended') {
      this.audioContext.resume();
    }
  }

  // 销毁资源
  destroy() {
    if (this.audioContext) {
      this.audioContext.close();
    }
    this.audioBuffers.clear();
  }
}

// 创建单例实例
const audioPlayer = new AudioPlayer();

// 监听页面可见性变化，恢复音频上下文
document.addEventListener('visibilitychange', () => {
  if (!document.hidden) {
    audioPlayer.resumeAudioContext();
  }
});

export default audioPlayer;